package cn.com.joyplus.wechat.service;

import cn.com.joyplus.wechat.configuration.CacheConfig;
import cn.com.joyplus.wechat.model.WechatContext;
import cn.com.joyplus.wechat.model.WechatUser;
import cn.com.joyplus.wechat.utils.Constant;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by 王灏川(wangrs@qq.com) on 2017/8/11 0011.
 */

@Service
@SuppressWarnings("unchecked")
public class WechatUserApiService {

    @Autowired
    RemoteResourceService remoteResourceService;

    @Autowired
    WechatCoreApiService wechatCoreApiService;

    @Autowired
    WechatCommonApiService wechatCommonApiService;

    @Autowired
    private WechatContext wechatContext;

    /**
     * 尤其注意：由于授权操作安全等级较高，所以在发起授权请求时，微信会对授权链接做正则强匹配校验，如果链接的参数顺序不对，授权页面将无法正常访问
     * https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
     *
     * @param code
     * @return
     * @throws Exception
     */
    @Cacheable(value = CacheConfig.CACHE_FOR_DEFAULT, unless = "#result == null")
    public String getOpenId(String code) throws Exception {
        String result = remoteResourceService.getRemoteResource(
                String.format("%s./sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                        Constant.WECHAT_API_BASE_URL, wechatContext.getAppId(), wechatContext.getAppSecret(), code));
        Map<String, String> map = new ObjectMapper().readValue(result, Map.class);
        if (map.containsKey("openid")) {
            return map.get("openid");
        } else {
            return null;
        }
    }


    @Cacheable(value = CacheConfig.CACHE_FOR_DEFAULT, key = "'allWechatUser'", unless = "#result == null")
    public List<WechatUser> getAllUsers() throws Exception {
        //获取关注用户OpenId,
        //https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840
        String userOpenIds = wechatCommonApiService.callCommonApi("getAllUserOpenids");
        JsonNode rootNode = new ObjectMapper().readTree(userOpenIds);
        JsonNode openidsNode = rootNode.get("data").get("openid");

        //构造批量获取用户详情的post参数
        //https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
        StringBuilder batchgetParams = new StringBuilder();
        openidsNode.forEach((JsonNode node) -> {
            if (batchgetParams.length() > 0) batchgetParams.append(",");
            batchgetParams.append(String.format("{\"openid\":")).append(node.toString()).append("}");
        });

        batchgetParams.insert(0, "{\"user_list\": [").append("]}");

        //批量获取用户详情
        String userDetails = wechatCommonApiService.callCommonApi("getAllUserDetail", batchgetParams.toString());


        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        return objectMapper.readValue(new ObjectMapper().readTree(userDetails).get("user_info_list").toString(),
                new TypeReference<List<WechatUser>>() {
                });

    }


}
